<template>
  <div id="login">
    <div class="login-wrap">
      <ul class="menu-tab">
        <li
          :class="{ current: item.current }"
          v-for="item in menuTab"
          :key="item.id"
          @click="toggleMenu(item)"
        >
          {{ item.txt }}
        </li>
      </ul>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        class="login-form"
        label-position="top"
        size="medium"
      >
        <el-form-item prop="username" class="item-form">
          <label>邮箱</label>
          <el-input
            type="text"
            v-model="ruleForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password" class="item-form">
          <label>密码</label>
          <el-input
            type="password"
            v-model="ruleForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="password2"
          class="item-form"
          v-if="model === 'register'"
        >
          <label>重复密码</label>
          <el-input
            type="password"
            v-model="ruleForm.password2"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code" class="item-form">
          <label>验证码</label>
          <el-row :gutter="10">
            <el-col :span="15">
              <el-input
                v-model="ruleForm.code"
                minlength="6"
                maxlength="6"
              ></el-input>
            </el-col>
            <el-col :span="9">
              <el-button
                type="success"
                class="block"
                @click="getSMS()"
                :disabled="codeButtonStatus.status"
                >{{ codeButtonStatus.text }}</el-button
              >
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button
            :disabled="loginButtonStatus"
            type="danger"
            @click="submitForm('ruleForm')"
            class="login-btn block"
            >{{ model == "login" ? "登录" : "注册" }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { GetSMS, Register, Login } from "@/api/login";
import { validateEmail, validatePass, validateVCode } from "@/utils/validate";
import { reactive, ref, onMounted } from "@vue/composition-api";

export default {
  name: "login",
  setup(props, { refs, root }) {
    let validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入用户名"));
      } else if (validateEmail(value)) {
        callback(new Error("请输入正确的邮箱地址"));
      } else {
        callback();
      }
    };
    let validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (validatePass(value)) {
        callback(new Error("密码为6至20位数字+字母"));
      } else {
        callback();
      }
    };

    let validatePassword2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入确认密码"));
      } else if (value != ruleForm.password) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };

    var validateCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("验证码不能为空"));
      } else if (validateVCode(value)) {
        return callback(new Error("验证码格式有误"));
      } else {
        callback();
      }
    };

    /////////////////////////////声明数据/////////////////////////////////////

    const menuTab = reactive([
      { txt: "登录", current: true, type: "login" },
      { txt: "注册", current: false, type: "register" }
    ]);

    const model = ref("login");

    const loginButtonStatus = ref(true);
    const codeText = ref("获取验证码");

    //验证码按钮状态
    const codeButtonStatus = reactive({
      status: false,
      text: "获取验证码"
    });

    //倒计时
    const timer = ref(null);

    //表单绑定数据
    const ruleForm = reactive({
      username: "",
      password: "",
      password2: "",
      code: ""
    });

    /**
     * 表单验证
     */
    const rules = reactive({
      username: [{ validator: validateUsername, trigger: "blur" }],
      password: [{ validator: validatePassword, trigger: "blur" }],
      password2: [{ validator: validatePassword2, trigger: "blur" }],
      code: [{ validator: validateCode, trigger: "blur" }]
    });

    /**
     * 生命函数
     */

    const toggleMenu = data => {
      model.value = data.type;
      menuTab.forEach(element => {
        element.current = false;
        data.current = true;
      });
      resetFromData();
      clearCountDown();
    };

    // 清除表单数据
    const resetFromData = () => {
      // 重置表单
      // this.$refs[formName].resetFields(); //2.0
      refs.ruleForm.resetFields(); // 3.0
    };

    // 更新按钮状态
    // const updataButtonStatus = params => {
    //   codeButtonStatus.status = params.status;
    //   codeButtonStatus.text = params.text;
    // };

    /**
     * 获取验证码
     */

    const getSMS = () => {
      if (ruleForm.username == "") {
        root.$message.error("邮箱不能为空");
        return false;
      }

      let params = {
        username: ruleForm.username,
        module: model.value
      };

      codeButtonStatus.status = true;
      codeButtonStatus.text = "发送中";

      GetSMS(params)
        .then(response => {
          console.log(response);
          loginButtonStatus.value = false;
          let data = response.data;
          root.$message({
            message: data.message,
            type: "success"
          });
          // 启用登录或注册按钮
          loginButtonStatus.value = false;

          //调用定时器
          countDown(10);
        })
        .catch(error => {
          if (error.resCode == 200) {
            codeButtonStatus.status = false;
            codeButtonStatus.text = "重新获取";
          }
        });
    };

    /**
     * 登录
     */
    const login = () => {
      let params = {
        username: ruleForm.username,
        password: ruleForm.password,
        code: ruleForm.code
      };

      root.$store.dispatch('app/login',params).then(resposne=>{
        //登录成功，页面跳转
        root.$router.push({
          name:'Console'
        })
      }).catch(error=>{

      });
    };
    /**
     * 注册
     */
    const register = () => {
      let param = {
        username: ruleForm.username,
        password: ruleForm.password,
        code: ruleForm.code,
        module: "register"
      };
      Register(param)
        .then(response => {
          let data = response.data;
          root.$message({
            message: data.message,
            type: "success"
          });
          //注册成功
          toggleMenu(menuTab[0]);
          clearCountDown();
        })
        .catch(error => {
          console.log(error);
        });
    };
    /**
     * 倒计时
     */
    const countDown = number => {
      if (timer.value) {
        clearInterval(timer.value);
      }

      let time = number;
      timer.value = setInterval(() => {
        time--;
        if (time === 0) {
          clearInterval(timer.value);
          codeButtonStatus.status = false;
          codeButtonStatus.text = "再次获取";
        } else {
          codeButtonStatus.text = `倒计时${time}秒`;
        }
      }, 1000);
    };

    /**
     * 清除倒计时
     */

    const clearCountDown = () => {
      codeButtonStatus.status = false;
      codeButtonStatus.text = "获取验证码";

      //清楚倒计时
      clearInterval(timer.value);
    };

    /**
     * 提交表单
     */
    const submitForm = formName => {
      refs[formName].validate(valid => {
        if (valid) {
          model.value === "login" ? login() : register();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    };

    /**
     * 生命周期函数,对应2.0里的mounted
     */
    onMounted(() => {});

    return {
      menuTab,
      model,
      toggleMenu,
      submitForm,
      ruleForm,
      rules,
      getSMS,
      loginButtonStatus,
      codeButtonStatus,
      codeText
    };
  }
};
</script>

<style lang="scss" scoped>
#login {
  height: 100vh;
  background-color: #344a5f;
}

.login-wrap {
  width: 330px;
  margin: auto;
}

.menu-tab {
  text-align: center;
  li {
    display: inline-block;
    width: 88px;
    line-height: 36px;
    font-size: 14px;
    color: #fff;
    border-radius: 2px;
    cursor: pointer;
  }
}

.current {
  background-color: rgba(0, 0, 1, 0.1);
}
.login-form {
  margin-top: 29px;
  label {
    margin-bottom: 3px;
    display: block;
    font-size: 14px;
    color: #fff;
  }
}
.item-form {
  margin-bottom: 13px;
}
.block {
  display: block;
  width: 100%;
}
.login-btn {
  margin-top: 19px;
}
</style>
